/** * Create by mzq * Description: 账号管理 * Date: 2025/2/11 10:11 * Update:
2025/2/11 10:11 */

<template>
  <view class="account-management">
    <MyDiaLog
      :width="800"
      :visible="visible"
      :titleName="titleName"
      @close="handleClose">
      <template>
        <view class="header-wrapper">
          <view class="left-section">
            <checkbox-group @change="handleSelectAll">
              <label class="checkbox-label">
                <checkbox :checked="isAllSelected" />
                <text>全选</text>
              </label>
            </checkbox-group>
            <text
              class="batch-delete-text"
              :class="{ disabled: !selectedRows.length }"
              @click="handleBatchDeleteClick"
              >批量删除
            </text>
          </view>
        </view>

        <uni-table
          ref="table"
          :loading="loading"
          border
          stripe
          type="selection"
          emptyText="暂无更多数据"
          @selection-change="selectionChange">
          <uni-tr>
            <uni-th width="200" align="center">编号</uni-th>
            <uni-th width="200" align="center">用户名</uni-th>
            <uni-th width="204" align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in tableData" :key="index">
            <uni-td align="center">{{ item.id }}</uni-td>
            <uni-td align="center">
              <view class="name">{{ item.name }}</view>
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <text class="action-text" @click="handleEdit(item)">修改</text>
                <text
                  class="action-text delete-text"
                  :class="{ disabled: item.name === 'sysadmin' }"
                  @click="
                    item.name !== 'sysadmin' && handleDelete(item.id, item.name)
                  "
                  >删除
                </text>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <!-- 添加分页组件 -->
        <view class="pagination-wrapper">
          <uni-pagination
            class="custom-pagination"
            :total="total"
            :pageSize="5"
            :current="currentPage"
            @change="handlePageChange"
            showIcon>
          </uni-pagination>
        </view>
      </template>
    </MyDiaLog>

    <EditManagement
      :visible="showEditDialog"
      :userData="currentEditUser"
      @close="handleEditClose"
      @success="handleEditSuccess" />
  </view>
</template>

<script>
import MyDiaLog from '@/components/MyDiaLog/MyDiaLog.vue'
import { deleteById, readJsonFromFile } from '@/utils/fileUtil'
import EditManagement from '@/pages/userMenu/components/EditManagement.vue'

export default {
  name: 'AccountManagement',
  components: {
    EditManagement,
    MyDiaLog,
  },
  data() {
    return {
      visible: true,
      titleName: '账号管理',
      loading: false,
      tableData: [],
      selectedRows: [],
      isAllSelected: false,
      showEditDialog: false,
      currentEditUser: null,
      currentPage: 1,
      pageSize: 5,
      total: 0,
      originalData: [], // 存储原始数据
    }
  },

  methods: {
    /**
     * 表格选择变化时的回调
     * @param {Object} selection - 选择事件对象，包含选中行的索引信息
     * selection.detail.index 包含所有选中行的索引数组
     */
    selectionChange(selection) {
      console.log('selectionChange', selection)
      const selectedIndexes = selection.detail.index
      this.selectedRows = selectedIndexes.map((index) => this.tableData[index])
      this.isAllSelected = selectedIndexes.length === this.tableData.length
    },

    /**
     * 处理全选复选框的点击事件
     * @param {Object} e - 复选框变化事件对象
     * e.detail.value 包含复选框的选中状态
     */
    handleSelectAll(e) {
      const checked = e.detail.value.length > 0
      this.isAllSelected = checked

      if (checked) {
        this.$refs.table.selectionAll()
      } else {
        this.$refs.table.clearSelection()
      }
    },

    /**
     * 处理对话框关闭事件
     * 触发父组件的 close 事件
     */
    handleClose() {
      this.$emit('close')
    },

    /**
     * 清除表格选中状态
     */
    clearTableSelection() {
      this.$refs.table.clearSelection()
      this.selectedRows = []
      this.isAllSelected = false
    },

    /**
     * 处理单个用户删除
     * @param {string} id - 要删除的用户ID
     * @param {string} name - 用户名，用于判断是否是系统管理员
     */
    handleDelete(id, name) {
      if (name === 'sysadmin') {
        uni.showToast({
          title: '系统管理员账号不能删除',
          icon: 'none',
        })
        return
      }

      uni.showModal({
        title: '提示',
        content: '确定要删除该记录吗？',
        success: async (res) => {
          if (res.confirm) {
            await deleteById(id, '/sdcard/test/user.json')
            // 删除后重新获取数据
            await this.getUser()
            // 清除选中状态
            this.clearTableSelection()
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
          }
        },
      })
    },

    /**
     * 处理批量删除
     * 检查选中项中是否包含系统管理员
     * 获取所有选中用户的ID并进行删除
     */
    handleBatchDelete() {
      console.log('点击了批量')
      const hasSysAdmin = this.selectedRows.some(
        (row) => row.name === 'sysadmin'
      )
      if (hasSysAdmin) {
        uni.showToast({
          title: '系统管理员账号不能删除',
          icon: 'none',
        })
        return
      }

      uni.showModal({
        title: '提示',
        content: '确定要删除选中的记录吗？',
        success: async (res) => {
          if (res.confirm) {
            const selectedIds = this.selectedRows.map((row) => row.id)
            console.log('批量删除的ID：', selectedIds)

            // 执行批量删除
            for (const id of selectedIds) {
              deleteById(id, '/sdcard/test/user.json')
            }
            // 删除后重新获取数据
            await this.getUser()
            // 清除选中状态
            this.clearTableSelection()
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
          }
        },
      })
    },

    /**
     * 处理分页变化
     */
    handlePageChange(e) {
      this.currentPage = e.current
      this.updateTableData()
    },

    /**
     * 更新表格数据
     */
    updateTableData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.tableData = this.originalData.slice(start, end)
    },

    /**
     * 从本地json文件获取用户信息
     */
    async getUser() {
      try {
        const res = await readJsonFromFile('/sdcard/test/user.json')
        console.log('acc', res)
        // 保存原始数据
        this.originalData = [...res].reverse()
        // 设置总数
        this.total = this.originalData.length
        // 更新表格数据
        this.updateTableData()
      } catch (error) {
        console.error('获取用户数据失败：', error)
        this.tableData = []
        this.total = 0
      }
    },

    /**
     * 处理编辑按钮点击
     * @param {Object} user - 要编辑的用户数据
     */
    handleEdit(user) {
      console.log('点击了', user)
      this.currentEditUser = user
      this.showEditDialog = true
      this.$nextTick(() => {
        if (this.$refs.editManagement) {
          this.$refs.editManagement.userForm = { ...user }
        }
      })
    },

    /**
     * 处理编辑对话框关闭
     */
    handleEditClose() {
      this.showEditDialog = false
      this.currentEditUser = null
    },

    /**
     * 处理编辑成功
     * 重新获取用户列表数据
     */
    handleEditSuccess() {
      this.handleEditClose()
      this.getUser()
    },

    /**
     * 添加新的方法处理点击事件
     */
    handleBatchDeleteClick() {
      if (this.selectedRows.length) {
        this.handleBatchDelete()
      }
    },
  },
  mounted() {
    this.getUser()
  },
}
</script>

<style scoped lang="scss">
.header-wrapper {
  margin-bottom: 10px;

  .left-section {
    display: flex;
    align-items: center;

    .checkbox-label {
      display: flex;
      align-items: center;

      checkbox {
        transform: scale(0.7);
      }

      text {
        margin-left: 4px;
        line-height: 1;
      }
    }

    .batch-delete-text {
      margin-left: 20px;
      color: #333;
      font-size: 14px;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      padding: 4px 12px;
      border-radius: 4px;

      &:hover {
        color: #f56c6c;
        border-color: #f56c6c;
      }

      &.disabled {
        color: #999;
        border-color: #dcdfe6;
        cursor: not-allowed;

        &:hover {
          color: #999;
          border-color: #dcdfe6;
        }
      }
    }
  }
}

.uni-button[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}

.uni-group {
  display: flex;
  justify-content: center;
  gap: 15px; // 设置文字之间的间距

  .action-text {
    font-size: 14px;
    color: #333;
    cursor: pointer;

    &:hover {
      color: #409eff; // 鼠标悬浮时的颜色
    }

    &.delete-text {
      &:hover {
        color: #f56c6c; // 删除文字悬浮时的颜色
      }

      &.disabled {
        color: #999;
        cursor: not-allowed;

        &:hover {
          color: #999;
        }
      }
    }
  }
}

.name {
  text-align: center;
}

.account-management {
  position: relative;

  .uni-tr {
    .uni-th {
      background-color: #f5f7fa !important; // 设置表头背景色为浅灰色
    }
  }
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 10px 0;

  /deep/ .custom-pagination {
    .uni-pagination__btn {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0;
      margin: 0 4px;
      text-align: center;
      display: inline-block;
      box-sizing: border-box;
      background: #fff;

      &:hover {
        color: #409eff;
        border-color: #409eff;
      }
    }

    .uni-pagination__num {
      margin: 0 8px;
    }

    .uni-pagination__num-tag {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 0 4px;
      margin: 0 4px;
      text-align: center;
      display: inline-block;
      box-sizing: border-box;
      background: #fff;
      cursor: pointer;

      &:hover {
        color: #409eff;
        border-color: #409eff;
      }

      &.page--active {
        background-color: #409eff !important;
        color: #fff !important;
        border-color: #409eff !important;
        font-weight: bold;

        &:hover {
          color: #fff !important;
        }
      }
    }

    .uni-pagination__num-current-text {
      &.current-index-text {
        color: #409eff !important;
        font-weight: bold;
      }
    }

    .page-text {
      font-size: 14px;
      color: #606266;
    }

    .uni-pagination__total {
      font-size: 14px;
      color: #606266;
      margin-right: 12px;
    }
  }
}
</style>
